﻿using Microsoft.Web.WebView2.WinForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter.Htm
{
    internal class HtmHeadingMarker
    {
        private WebView2 m_webView;
        private CatalogTreeHandler m_catalogTreeHandler;
        private string m_outputMarkdownPath;

        public HtmHeadingMarker(CatalogTreeHandler catalogTreeHandler)
        {
            m_catalogTreeHandler = catalogTreeHandler;
        }

        public void InitWidget(TableLayoutControlCollection controls)
        {
            // 初始化WebView2控件
            m_webView = new WebView2();
            m_webView.Dock = DockStyle.Fill;
            //m_webView.Location = new Point(0, 0);
            //m_webView.MinimumSize = new Size(20, 20);

            // 将WebView2控件添加到窗体
            controls.Add(m_webView, 1, 0);
        }

        public async Task ReadText(string filePath)
        {
            m_outputMarkdownPath = Path.ChangeExtension(filePath, ".md");
            try
            {
                // 使用WebView2控件显示HTM文件
                if (m_webView != null)
                {
                    // 直接导航到文件路径
                    await m_webView.EnsureCoreWebView2Async();
                    m_webView.Source = new Uri(filePath);
                    // 调整WebView2的位置，使其显示在工具栏下方
                    m_webView.Dock = DockStyle.Fill;
                }
                else
                {
                    MessageBox.Show("WebView2控件未初始化", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载HTM文件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public async void ApplyHeadingStyle(int headingLevel)
        {
            try
            {
                // 确保WebView2已加载完成且有文档
                if (m_webView == null || m_webView.CoreWebView2 == null)
                {
                    MessageBox.Show("文档尚未加载完成，请稍后再试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取当前选中的文本
                string selection = await m_webView.ExecuteScriptAsync(ScriptUtils.GetScript_GetSelection());
                selection = selection.Replace("\\\"", "\""); // 修正selection字符串格式
                selection = selection.Trim('"'); // 移除首尾多余的双引号
                HtmSelectionObject htmSelectionObject = JsonConvert.DeserializeObject<HtmSelectionObject>(selection);
                if (string.IsNullOrEmpty(selection))
                {
                    MessageBox.Show("请先选择要设置为标题的文本。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建JavaScript代码，将选中的文本替换为带有标题标签的文本或正文
                string script;

                if (headingLevel == 0)
                {
                    // 处理正文样式
                    script = ScriptUtils.GetScript_SetAsNormalText();
                }
                else
                {
                    script = ScriptUtils.GetScript_SetAsHeading(headingLevel);
                }

                // 执行JavaScript代码
                string result = await m_webView.ExecuteScriptAsync(script);

                //await Identify();

                if (result.ToLower() == "true")
                {
                    if (headingLevel > 0)
                    {
                        if (headingLevel == 1)
                        {
                            m_catalogTreeHandler.HandleHeadingLevel1(htmSelectionObject);
                        }
                        else if (headingLevel == 2)//二级
                        {
                            m_catalogTreeHandler.HandleHeadingLevel2(htmSelectionObject);
                        }
                        else//三级
                        {
                            m_catalogTreeHandler.HandleHeadingLevel3(htmSelectionObject);
                        }
                    }
                }
                else
                {
                    string styleType = headingLevel == 0 ? "正文" : $"标题{headingLevel}";
                    MessageBox.Show($"应用{styleType}样式失败，请重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"应用样式时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public async Task ConvertToMarkdown()
        {
            HtmToMarkdownConverter converter = new HtmToMarkdownConverter(m_webView, m_outputMarkdownPath);
            await converter.SaveAsMarkdown();
        }
    }
}
